package org.szy.plugin.gen.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.ClasspathResourceLoader;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.ProxyComponent;
import org.noear.solon.data.annotation.Tran;
import org.szy.core.common.enums.CommonYorNEnum;
import org.szy.core.common.exception.BaseException;
import org.szy.core.common.page.QueryPage;
import org.szy.core.common.service.impl.BaseServiceImpl;
import org.szy.core.common.uilts.DownloadUtil;
import org.szy.plugin.gen.entity.GenBasic;
import org.szy.plugin.gen.entity.GenConfig;
import org.szy.plugin.gen.mapper.GenBasicMapper;
import org.szy.plugin.gen.param.GenBasicQueryParam;
import org.szy.plugin.gen.result.GenBasicPreviewResult;
import org.szy.plugin.gen.result.GenBasicTableColumnResult;
import org.szy.plugin.gen.result.GenBasicTableResult;
import org.szy.plugin.gen.service.GenBasicService;
import org.szy.plugin.gen.service.GenConfigService;
import org.szy.plugin.gen.utils.GenDbTypeUtil;

import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.sql.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;

import static org.szy.plugin.gen.entity.table.GenBasicTableDef.GEN_BASIC;
import static org.szy.plugin.gen.entity.table.GenConfigTableDef.GEN_CONFIG;

/**
 * 生成基础 服务层实现。
 *
 * @author sunzhiyang
 * @since 2023-06-14
 */
@ProxyComponent
public class GenBasicServiceImpl extends BaseServiceImpl<GenBasicMapper, GenBasic> implements GenBasicService {

    private static final String GEN_PROJECT_PLUGIN_KEY = "szy-plugin";
    // 生成前端文件列表
    private static final List<JSONObject> GEN_FRONT_FILE_LIST = CollectionUtil.newArrayList(
            JSONUtil.createObj().set("name", "detail.html.btl").set("path", ""),
            JSONUtil.createObj().set("name", "edit.html.btl").set("path", ""),
            JSONUtil.createObj().set("name", "index.html.btl").set("path", ""));
    // 生成后端文件列表
    private static final List<JSONObject> GEN_BACKEND_FILE_LIST = CollectionUtil.newArrayList(
            JSONUtil.createObj().set("name", "Controller.java.btl").set("path", "controller"),
            JSONUtil.createObj().set("name", "Entity.java.btl").set("path", "entity"),
            JSONUtil.createObj().set("name", "Mapper.java.btl").set("path", "mapper"),
            JSONUtil.createObj().set("name", "QueryParam.java.btl").set("path", "param"),
            JSONUtil.createObj().set("name", "Service.java.btl").set("path", "service"),
            JSONUtil.createObj().set("name", "ServiceImpl.java.btl").set("path", "service" + File.separator + "impl"));
    private static final String SORT_CODE_KEY = "sort_code";
    private static final String DEL_FLAG = "del_flag";
    private static final String CREATE_USER_KEY = "create_user";
    private static final String CREATE_TIME_KEY = "create_time";
    private static final String UPDATE_USER_KEY = "update_user";
    private static final String UPDATE_TIME_KEY = "update_time";
    private static final String CLIENT_IP = "client_ip";
    private static final List<String> BASE_ENTITY = CollectionUtil.newArrayList(
            CREATE_USER_KEY, CREATE_TIME_KEY, UPDATE_USER_KEY, UPDATE_TIME_KEY, CLIENT_IP
    );
    private static String MODULE_KEY = "biz";

    @Inject
    private DataSource dataSource;
    @Inject
    private GenBasicService genBasicService;
    @Inject
    private GenConfigService genConfigService;

    @Override
    public QueryWrapper qwByQuery(GenBasicQueryParam param) {
        QueryWrapper qw = new QueryWrapper();
        if (StrUtil.isNotEmpty(param.getDbTable())) qw.and(GEN_BASIC.DB_TABLE.eq(param.getDbTable()));
        return qw;
    }

    @Override
    public Page<GenBasic> pageQuery(QueryPage<GenBasic> page, GenBasicQueryParam param) {
        QueryWrapper qw = qwByQuery(param);
        return this.page(page, qw);
    }

    @Tran
    @Override
    public boolean add(GenBasic entity) {
        boolean save = this.save(entity);
        if (save) {
            createConfig(entity.getId());
        }
        return save;
    }

    @Tran
    @Override
    public boolean removeById(Serializable id) {
        genConfigService.removeByBasicId(id);
        return super.removeById(id);
    }

    @Override
    public List<GenBasicTableResult> tables() {
        Connection conn = null;
        ResultSet rs = null;
        try {
            //获取数据库连接
            conn = dataSource.getConnection();
            //获取数据库元数据
            DatabaseMetaData metaData = conn.getMetaData();
            //创建一个空的表列表
            List<GenBasicTableResult> tables = new ArrayList<>();
            //获取所有表
            rs = metaData.getTables(conn.getCatalog(), null, "%", new String[]{"TABLE", "VIEW"});
            //遍历所有表
            while (rs.next()) {
                //获取表名
                String tableName = rs.getString("TABLE_NAME");
                //创建一个表结果
                GenBasicTableResult genBasicTableResult = new GenBasicTableResult();
                //设置表名
                genBasicTableResult.setTableName(tableName);
                //获取表备注
                String remarks = rs.getString("remarks");
                //如果表备注为空，设置表备注为表名
                if (ObjectUtil.isEmpty(remarks))
                    genBasicTableResult.setTableRemark(tableName);
                    //否则设置表备注
                else
                    genBasicTableResult.setTableRemark(remarks);

                //将表结果添加到表列表中
                tables.add(genBasicTableResult);
            }
            //返回表列表
            return tables;
        } catch (SQLException sqlException) {
            //打印异常信息
            sqlException.printStackTrace();
            //抛出异常
            throw new BaseException("获取数据库表失败");
        } finally {
            try {
                if (rs != null) rs.close();
                if (conn != null) conn.close();
                //关闭资源
                if (rs != null) rs.close();
                if (conn != null) conn.close();
            } catch (Exception e) {
                //打印异常信息
                e.printStackTrace();
            }
        }
    }

    @Override
    public List<GenBasicTableColumnResult> tableColumns(String dbTable) {
        Connection conn = null;
        ResultSet rs = null;
        try {
            // 获取数据库连接
            conn = dataSource.getConnection();
            // 获取数据库元数据
            DatabaseMetaData metaData = conn.getMetaData();
            // 创建一个存放表字段信息的列表
            List<GenBasicTableColumnResult> columns = new ArrayList<>();
            // 遍历表中的每一列
            rs = metaData.getColumns(conn.getCatalog(), null, dbTable, "%");
            while (rs.next()) {
                // 获取列名
                String columnName = rs.getString("COLUMN_NAME");
                // 获取列描述
                ResultSetMetaData metaData1 = rs.getMetaData();
                GenBasicTableColumnResult columnResult = new GenBasicTableColumnResult();
                // 设置列名
                columnResult.setColumnName(columnName);
                // 获取列描述
                String remarks = rs.getString("REMARKS");
                if (ObjectUtil.isEmpty(remarks))
                    columnResult.setColumnRemark(columnName);
                else
                    columnResult.setColumnRemark(remarks);

                // 获取列类型
                String typeName = rs.getString("TYPE_NAME");
                if (ObjectUtil.isEmpty(typeName))
                    columnResult.setTypeName("none");
                else
                    columnResult.setTypeName(typeName.toLowerCase());

                // 获取列大小
                String columnSize = rs.getString("COLUMN_SIZE");
                columnResult.setColumnSize(columnSize);
                // 获取列是否可为空
                Integer nullable = rs.getInt("NULLABLE");
                columnResult.setNullable(nullable);

                // 将列信息添加到列表中
                columns.add(columnResult);
            }
            return columns;
        } catch (SQLException sqlException) {
            sqlException.printStackTrace();
            throw new BaseException("获取数据库表字段失败，表名称：{}", dbTable);
        } finally {
            try {
                if (rs != null) rs.close();
                if (conn != null) conn.close();
                // 关闭连接
                if (rs != null) rs.close();
                if (conn != null) conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Tran
    @Override
    public boolean createConfig(Serializable id) {
        GenBasic entity = this.getById(id);
        if (entity == null) return false;
        // 删除以前的配置信息
        genConfigService.removeByBasicId(id);
        // 获取改表中所有字段的名称列表
        List<GenBasicTableColumnResult> resultList = this.tableColumns(entity.getDbTable());
        if (ObjectUtil.isEmpty(resultList)) return false;
//        ListUtil.reverse(resultList);
        for (int i = 0; i < resultList.size(); i++) {
            GenBasicTableColumnResult item = resultList.get(i);
            GenConfig addParam = new GenConfig();
            addParam.setBasicId(entity.getId());
            // 判断是否是主键
            if (item.getColumnName().equals(entity.getDbTableKey())) {
                addParam.setIsTableKey(CommonYorNEnum.Y.getKey());
            } else {
                addParam.setIsTableKey(CommonYorNEnum.N.getKey());
            }
            // 字段名称
            addParam.setFieldName(item.getColumnName());
            // 字段类型
            addParam.setFieldType(item.getTypeName());
            // 字段描述
            addParam.setFieldRemark(item.getColumnRemark());
            // 字段大小
            addParam.setFieldSize(item.getColumnSize());
            // 字段Java类型
            addParam.setFieldJavaType(GenDbTypeUtil.getJavaTypeBySqlType(item.getTypeName()));
            // 页面效果类型
            addParam.setEffectType(GenDbTypeUtil.getEffectTypeBySqlType(item.getTypeName()));
            // 除主键、删除标志、创建人、创建时间、修改人和修改时间外，所有默认在列表显示、在增改显示、非列省略、非必填，非查询
            if (entity.getDbTableKey().equals(item.getColumnName())
                    || StrUtil.equalsAny(item.getColumnName(), DEL_FLAG, CREATE_USER_KEY, CREATE_TIME_KEY, UPDATE_USER_KEY, UPDATE_TIME_KEY, CLIENT_IP)) {
                // 设置在列表不显示
                addParam.setWhetherTable(CommonYorNEnum.N.getKey());
                // 设置是否可以添加或更新
                addParam.setWhetherAddUpdate(CommonYorNEnum.N.getKey());
            } else {
                addParam.setWhetherTable(CommonYorNEnum.Y.getKey());
                addParam.setWhetherAddUpdate(CommonYorNEnum.Y.getKey());
            }
            // 列省略
            addParam.setWhetherRetract(CommonYorNEnum.N.getKey());
            // 查询
            addParam.setQueryWhether(CommonYorNEnum.N.getKey());
            // 是否必填
            addParam.setWhetherRequired(Objects.equals(item.getNullable(), CommonYorNEnum.Y.getKey()) ? CommonYorNEnum.N.getKey() : CommonYorNEnum.Y.getKey());
            // 排序
            addParam.setSortCode(i);
            GenConfig genConfig = BeanUtil.toBean(addParam, GenConfig.class);
            genConfigService.save(genConfig);
        }

        return true;
    }

    @Override
    public boolean execGenPro(Long id) {
        File tempFolder = this.genTempFolder(id, false);
        String genPath = System.getProperty("user.dir") + File.separator + "genTemp" + File.separator + "src" + File.separator + "main";
        // 定义前端生成的目录
        String genProjectFrontendPath = genPath + File.separator + "templates";

        if (!FileUtil.exist(genProjectFrontendPath)) {
            FileUtil.mkdir(genProjectFrontendPath);
        }
        // 定义后端生成的目录
        String genProjectBackendPath = genPath + File.separator + "java";
        if (!FileUtil.exist(genProjectBackendPath)) {
            FileUtil.mkdir(genProjectBackendPath);
        }
        try {
            //前端代码移动到前端
            FileUtil.moveContent(FileUtil.file(tempFolder + File.separator + "frontend"), FileUtil.file(genProjectFrontendPath), true);

            // 后端代码移动到后端
            FileUtil.moveContent(FileUtil.file(tempFolder + File.separator + "backend"), FileUtil.file(genProjectBackendPath), true);

            // 移动完毕删除临时目录
            FileUtil.del(tempFolder);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("代码生成异常");
        }
        return true;
    }

    @Override
    public void execGenZip(Long id) throws IOException {
        File tempFolder = this.genTempFolder(id, true);
        if (tempFolder == null) {
            throw new BaseException("代码生成基础不存在，id值为：{}", id);
        }
        // 压缩
        File zip = ZipUtil.zip(tempFolder);
        // 压缩完毕删除临时目录
        FileUtil.del(tempFolder);
        // 下载
        DownloadUtil.download(zip);
    }

    /**
     * 获取临时文件夹
     *
     * @param id    生成配置ID
     * @param isZip 是否是压缩包
     * @return 临时文件夹
     */
    private File genTempFolder(Long id, boolean isZip) {
        GenBasic basic = this.getById(id);
        if (ObjectUtil.isEmpty(basic)) {
            if (isZip) {
                return null;
            } else {
                // 否则可以直接抛出异常
                throw new BaseException("代码生成基础不存在，id值为：{}", id);
            }
        }
        //
        GenBasicPreviewResult genBasicPreviewResult = this.previewGen(id);
        // 先删除压缩包
        if (isZip) FileUtil.del(FileUtil.getTmpDirPath() + File.separator + basic.getFunctionName() + ".zip");
        // 生成临时目录
        File tempFolder = FileUtil.file(FileUtil.getTmpDirPath() + File.separator + basic.getFunctionName());
// 生成前端代码到临时目录
        genBasicPreviewResult.getGenBasicCodeFrontendResultList().forEach(genBasicCodeResult ->
                FileUtil.writeUtf8String(genBasicCodeResult.getCodeFileContent(), FileUtil.file(tempFolder + File.separator
                        + "frontend" + File.separator + genBasicCodeResult.getCodeFileWithPathName())));
        // 生成后端代码到临时目录
        genBasicPreviewResult.getGenBasicCodeBackendResultList().forEach(genBasicCodeResult ->
                FileUtil.writeUtf8String(genBasicCodeResult.getCodeFileContent(), FileUtil.file(tempFolder + File.separator
                        + "backend" + File.separator + genBasicCodeResult.getCodeFileWithPathName())));
        return tempFolder;
    }

    private GenBasicPreviewResult previewGen(Long id) {
        GenBasic basic = this.getById(id);
        // 构建参数
        JSONObject bindingJsonObject = this.getBindingJsonObject(basic);
        GenBasicPreviewResult result = new GenBasicPreviewResult();

        try {

            // 前端基础路径
            String genFrontBasicPath = "";
            // 前端
            GroupTemplate groupTemplateFront = new GroupTemplate(new ClasspathResourceLoader("frontend"),
                    Configuration.defaultConfiguration());
            List<GenBasicPreviewResult.GenBasicCodeResult> genBasicCodeFrontendResultList = CollectionUtil.newArrayList();
            GEN_FRONT_FILE_LIST.forEach(fileJsonObject -> {
                String fileTemplateName = fileJsonObject.getStr("name");
                String fileTemplatePath = MODULE_KEY;
                GenBasicPreviewResult.GenBasicCodeResult genBasicCodeFrontResult = new GenBasicPreviewResult.GenBasicCodeResult();
                Template templateFront = groupTemplateFront.getTemplate(fileTemplateName);
                templateFront.binding(bindingJsonObject);
                String resultName = StrUtil.removeSuffix(fileTemplateName, ".btl");
                genBasicCodeFrontResult.setCodeFileName(resultName);
                genBasicCodeFrontResult.setCodeFileWithPathName(genFrontBasicPath + fileTemplatePath + File.separator + basic.getBusName() + File.separator + resultName);
                genBasicCodeFrontResult.setCodeFileContent(templateFront.render());
                genBasicCodeFrontendResultList.add(genBasicCodeFrontResult);
            });
            result.setGenBasicCodeFrontendResultList(genBasicCodeFrontendResultList);

            // 后端基础路径
            String genBackendBasicPath = StrUtil.replace(basic.getPackageName(), StrUtil.DOT, File.separator) + File.separator;
            // 后端
            GroupTemplate groupTemplateBackEnd = new GroupTemplate(new ClasspathResourceLoader("backend"),
                    Configuration.defaultConfiguration());
            List<GenBasicPreviewResult.GenBasicCodeResult> genBasicCodeBackendResultList = CollectionUtil.newArrayList();
            for (JSONObject object : GEN_BACKEND_FILE_LIST) {
                String fileTemplateName = object.getStr("name");
                String fileTemplatePath = object.getStr("path");
                GenBasicPreviewResult.GenBasicCodeResult genBasicCodeBackendResult = new GenBasicPreviewResult.GenBasicCodeResult();
                Template templateBackend = groupTemplateBackEnd.getTemplate(fileTemplateName);
                templateBackend.binding(bindingJsonObject);
                String resultName = StrUtil.removeSuffix(fileTemplateName, ".btl");
                if (fileTemplateName.equalsIgnoreCase("Entity.java.btl")) {
                    resultName = ".java";
                }
                genBasicCodeBackendResult.setCodeFileName(basic.getClassName() + resultName);
                genBasicCodeBackendResult.setCodeFileWithPathName(genBackendBasicPath + fileTemplatePath + File.separator + basic.getClassName() + resultName);
                genBasicCodeBackendResult.setCodeFileContent(templateBackend.render());
                genBasicCodeBackendResultList.add(genBasicCodeBackendResult);
            }
            result.setGenBasicCodeBackendResultList(genBasicCodeBackendResultList);

        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("代码生成异常");
        }

        return result;
    }

    /**
     * 根据代码生成基础获取构造的参数
     */
    private JSONObject getBindingJsonObject(GenBasic basic) {
        JSONObject bindingJsonObject = JSONUtil.createObj();
        String[] dbTables = basic.getDbTable().split("_");
        MODULE_KEY = dbTables[0];
        // 代码模块名
        bindingJsonObject.set("moduleName", MODULE_KEY);
        // 功能名
        bindingJsonObject.set("functionName", basic.getFunctionName());
        // 业务名
        bindingJsonObject.set("busName", basic.getBusName());
        // 包名
        bindingJsonObject.set("packageName", basic.getPackageName());
        // 库名
        bindingJsonObject.set("dbTable", basic.getDbTable());
        // 全大写库名
        bindingJsonObject.set("dbTableUpperCase", basic.getDbTable().toUpperCase(Locale.ROOT));
        // 类名
        bindingJsonObject.set("className", basic.getClassName());
        // 类首字母小写名
        bindingJsonObject.set("classNameFirstLower", StrUtil.lowerFirst(basic.getClassName()));
        // 主键名
        bindingJsonObject.set("dbTableKey", basic.getDbTableKey());
        // 主键Java类型
        bindingJsonObject.set("dbTableKeyJavaType", "String");
        // 主键名驼峰
        bindingJsonObject.set("dbTableKeyCamelCase", StrUtil.toCamelCase(basic.getDbTableKey().toLowerCase()));
        // 主键首字母大写名
        bindingJsonObject.set("dbTableKeyFirstUpper", StrUtil.upperFirst(basic.getDbTableKey().toLowerCase()));
        // 主键注释
        bindingJsonObject.set("dbTableKeyRemark", basic.getDbTableKey());
        // 作者
        bindingJsonObject.set("authorName", basic.getAuthorName());
        // 生成时间
        bindingJsonObject.set("genTime", DateUtil.now());
        // 定义配置详情列表
        List<JSONObject> configList = CollectionUtil.newArrayList();
        // 定义是否有排序字段
        AtomicBoolean hasSortCodeField = new AtomicBoolean(false);
        genConfigService.list(GEN_CONFIG.BASIC_ID.eq(basic.getId()))
                .forEach(genConfig -> {
                    if (BASE_ENTITY.contains(genConfig.getFieldName())) {
                        return;
                    }
                    // 定义字段信息
                    JSONObject configItem = JSONUtil.createObj();
                    if (genConfig.getFieldName().equalsIgnoreCase(SORT_CODE_KEY)) {
                        hasSortCodeField.set(true);
                    }
                    // 如果是主键，则无需作为添加参数，需要作为编辑参数，需要主键注解
                    if (genConfig.getFieldName().equalsIgnoreCase(basic.getDbTableKey())) {
                        configItem.set("needAdd", false);
                        configItem.set("needEdit", true);
                        configItem.set("needQuery", false);
                        configItem.set("needQueryType", "none");
                        configItem.set("required", true);
                        configItem.set("needTableId", true);
                        configItem.set("delFlag", false);
                        bindingJsonObject.set("dbTableKeyJavaType", genConfig.getFieldJavaType());
                        bindingJsonObject.set("dbTableKeyRemark", genConfig.getFieldRemark());
                    } else {
                        // 排除删除标志
                        if (genConfig.getFieldName().equalsIgnoreCase(DEL_FLAG)) {
                            configItem.set("needAdd", false);
                            configItem.set("needEdit", false);
                            configItem.set("needQuery", false);
                            configItem.set("needQueryType", "none");
                            configItem.set("required", false);
                            configItem.set("needTableId", false);
                            configItem.set("delFlag", true);
                        } else {
                            Integer needAddAndUpdate = genConfig.getWhetherAddUpdate();
                            configItem.set("needAdd", needAddAndUpdate);
                            configItem.set("needEdit", needAddAndUpdate);
                            configItem.set("needQuery", genConfig.getQueryWhether());
                            configItem.set("needQueryType", genConfig.getQueryType());
                            configItem.set("required", genConfig.getWhetherRequired());
                            configItem.set("needTableId", false);
                            configItem.set("delFlag", false);
                        }
                    }
                    // 列显示
                    configItem.set("whetherTable", genConfig.getWhetherTable());
                    // 列省略
                    configItem.set("whetherRetract", genConfig.getWhetherRetract());
                    // 增改
                    configItem.set("whetherAddUpdate", genConfig.getWhetherAddUpdate());
                    // 作用类型
                    configItem.set("effectType", genConfig.getEffectType());
                    // 字典值
                    configItem.set("dictTypeCode", genConfig.getDictTypeCode());
                    // 实体类型
                    configItem.set("fieldJavaType", genConfig.getFieldJavaType());
                    // 字段全大写
                    configItem.set("fieldNameUpperCase", genConfig.getFieldName().toUpperCase(Locale.ROOT));
                    // 字段驼峰名
                    configItem.set("fieldNameCamelCase", StrUtil.toCamelCase(genConfig.getFieldName().toLowerCase()));
                    // 字段驼峰首字母大写名
                    configItem.set("fieldNameCamelCaseFirstUpper", StrUtil.upperFirst(StrUtil.toCamelCase(genConfig.getFieldName().toLowerCase())));
                    // 字段注释
                    configItem.set("fieldRemark", genConfig.getFieldRemark());
                    // 字段长度
                    configItem.set("fieldSize", genConfig.getFieldSize());
                    // 是否需要自动插入
                    configItem.set("baseEntity", BASE_ENTITY.contains(genConfig.getFieldName()));
                    configList.add(configItem);

                });
        // 配置信息
        bindingJsonObject.set("configList", configList);
        // 有排序字段
        bindingJsonObject.set("hasSortCodeField", hasSortCodeField.get());
        return bindingJsonObject;
    }

    @Override
    public void textGen(String tableName, String tableRemark, String author, String packageName) throws IOException {

        String[] tables = tableName.split("_");
        String camelCase = StrUtil.toCamelCase(tableName);

        String busName = "";
        if (tables.length > 1) {
            busName = StrUtil.toCamelCase(StrUtil.join("_", (Object) Arrays.copyOfRange(tables, 1, tables.length)));
        }

        GenBasic genBasic = new GenBasic();
        genBasic.setAuthorName(author); // 作者
        genBasic.setDbTable(tableName); // 数据库表名
        genBasic.setBusName(busName); // 业务名
        genBasic.setClassName(StrUtil.upperFirst(StrUtil.toCamelCase(camelCase))); // 类名
        genBasic.setDbTableKey("id"); // 数据库表主键
        genBasic.setFunctionName(tableRemark); // 函数名称
        genBasic.setGenerateType(1); //  生成类型
        if (StrUtil.isEmpty(packageName)) {
            genBasic.setPackageName("org.szy." + tables[0]); //  包名
        } else {
            genBasic.setPackageName(packageName);
        }
        genBasic.setTablePrefix(1); //  表前缀
        genBasicService.add(genBasic);
        genBasicService.execGenPro(genBasic.getId());
        genBasicService.removeById(genBasic.getId());
    }
}
